package com.example.ywj.toutiao.fragments;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.example.ywj.toutiao.IssueActivity;
import com.example.ywj.toutiao.R;
import com.example.ywj.toutiao.SearchActivity;
import com.example.ywj.toutiao.bean.Key;
import com.example.ywj.toutiao.bean.Lists;
import com.example.ywj.toutiao.bean.Title;
import com.example.ywj.toutiao.utils.Constant;
import com.example.ywj.toutiao.utils.MyFragmentPageAdapte4;
import com.example.ywj.toutiao.utils.PopWindowAdapter1;
import com.example.ywj.toutiao.utils.ResponseApi;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class XGSPFragment extends Fragment {
    private static final String TAG = "XGSPFragment";
    public View view;
    public TextView fangdajing__xgsp,cam_xgsp;
    public EditText editText_xgsp;
    public ViewPager viewPager;
    public TabLayout tabLayout;
    public String baseUrl = Constant.BASEURL;
    public MyFragmentPageAdapte4 myFragmentPageAdapte4;
    public List<String> strTitle = new ArrayList<>();
    public PopupWindow popupWindow;
    public LinearLayout layout;
    public String[] add ={"发图文","拍小视频","发视频","提问","开直播","爆料"};
    public List<Lists> liststr = new ArrayList<>();
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(view == null){
            view = inflater.inflate(R.layout.xgsp_fragment, null);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = getActivity().getWindow();
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
            }
            initView();
            getKeyData();
            getData();
        }
        return view;
    }
    public void initView(){
        Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "iconfont.ttf");
        fangdajing__xgsp = view.findViewById(R.id.fangdajing__xgsp);
        cam_xgsp = view.findViewById(R.id.cam_xgsp);
        editText_xgsp = view.findViewById(R.id.editText_xgsp);
        viewPager = view.findViewById(R.id.viewpager_xgsp);
        tabLayout = view.findViewById(R.id.tabLayout_xgsp);
        fangdajing__xgsp.setTypeface(font);
        fangdajing__xgsp.setText(getResources().getString(R.string.font5));
        cam_xgsp.setTypeface(font);
        cam_xgsp.setText(getResources().getString(R.string.font6));
        cam_xgsp.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                int y = new Double(tabLayout.getBottom() * 3.6/ 2).intValue() ;
                int x = getActivity().getWindowManager().getDefaultDisplay().getWidth()-1050;
                Log.i(TAG, "onClick: "+x);
                showPopWindow(x,y);
            }
        });
    }
    public void getKeyData(){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.getKeyByType(1);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200&& obj.has("data")){
                    JsonArray data = obj.getAsJsonArray("data");
                    Gson gson = new Gson();
                    List<Key> list = gson.fromJson(data,new TypeToken<ArrayList<Key>>(){}.getType());
                    //Log.i(TAG, "onResponse: "+list);
                    int index = (int)(0+Math.random()*((list.size()-1)-0+1));
                    //Log.i(TAG, "onResponse: "+index);
                    String str = list.get(index).getKey();
                    Log.i(TAG, "onResponse: "+list.get(index).getKey());
                    //Log.i(TAG, "onResponse: "+str);
                    editText_xgsp.setHint(str);
                    editText_xgsp.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                        @Override
                        public void onFocusChange(View v, boolean hasFocus) {
                            if(hasFocus){
                                Bundle bundle = new Bundle();
                                //Log.i(TAG, "onFocusChange: "+et.getText().toString());

                                bundle.putString("key",String.valueOf(editText_xgsp.getHint()));
                                Intent intent = new Intent(v.getContext(),SearchActivity.class);
                                intent.putExtras(bundle);
                                startActivity(intent);
                                getActivity().overridePendingTransition(0, 0);
                                v.clearFocus();
                            }
                        }
                    });
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: 请求失败");
            }
        });
    }
    private void getData(){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.getData();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200 && obj.has("data")){
                    JsonArray data = obj.getAsJsonArray("data");
                    Gson gson = new Gson();
                    List<Title> list = gson.fromJson(data,new TypeToken<ArrayList<Title>>(){}.getType());
                    for(int i = 0;i<list.size();i++){
                        strTitle.add(list.get(i).getTitle());
                    }
                    addTabToTabLayout(strTitle);
                    tabLayout.setupWithViewPager(viewPager);
                    myFragmentPageAdapte4 = new MyFragmentPageAdapte4(getActivity().getSupportFragmentManager(),strTitle);
                    viewPager.setAdapter(myFragmentPageAdapte4);
                    viewPager.setOffscreenPageLimit(strTitle.size());
                }else {
                    Log.i(TAG, "onResponse: 出错了");
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: 请求失败");
            }
        });
    }
    private void addTabToTabLayout(List<String> list) {
        for (int i = 0; i < list.size(); i++) {
            tabLayout.addTab(tabLayout.newTab().setText(list.get(i)));
        }
    }
    public void showPopWindow(int x,int y){

        Integer picArr[] = {R.string.pic,R.string.huo,R.string.pvideo,R.string.ask,R.string.video,R.string.laba};
        for(int i=0;i<add.length;i++){
            liststr.add(new Lists(add[i],picArr[i]));
        }
        Log.i(TAG, "showPopWindow: "+liststr);
        PopWindowAdapter1 popWindowAdapter1 = new PopWindowAdapter1(liststr);
        layout = (LinearLayout) LayoutInflater.from(getContext()).inflate(
                R.layout.popwindow_layout, null);
        ListView listView = layout.findViewById(R.id.popListView);
        listView.setAdapter(popWindowAdapter1);
        popupWindow = new PopupWindow(getContext());
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#636363")));
        popupWindow
                .setWidth(new Double(getActivity().getWindowManager().getDefaultDisplay().getWidth() / 2.8).intValue());
        popupWindow.setHeight(860);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setContentView(layout);
        popupWindow.showAtLocation(getActivity().findViewById(R.id.toolbar),
                Gravity.TOP, x, y);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0:
                        Intent intent = new Intent(view.getContext(),IssueActivity.class);
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.translate_dialog_in,0);
                }
            }
        });
    }
}
